package controllers

import (
	"time"

	"git.oschina.net/goxiang2/web/admin/models"
	"github.com/astaxie/beego"
)

type LoginController struct {
	beego.Controller
}

func (c *LoginController) Get() {
	c.SetSession("user", nil)
	c.Data["title"] = beego.AppConfig.String("apptitle")
	c.Data["token"] = models.GetToken()

	if beego.AppConfig.String("run_test") == "true" {
		c.Data["lu"] = "guangbo"
		c.Data["lp"] = "ghb851019"
	}

	c.TplName = "login.ace"
}

type LoginInfo struct {
	Username string `form:"username"`
	Passward string `form:"pwd"`
}

func (c *LoginController) Post() {
	if !models.CheckToken(c.GetString("token")) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "操作失败，请重新刷新界面"}
		c.ServeJSON()
		return
	}

	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "帐号密码不能为空"}
		c.ServeJSON()
		return
	}

	user := models.GetUserByUsername(username)
	if user == nil || user.Password != password {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "密码错误"}
		c.ServeJSON()
		return
	}
	c.SetSession("user", &LoginInfo{username, password})

	user.LastLoginTs = time.Now().Unix()
	models.UpdateUser(user)

	c.Data["json"] = &map[string]interface{}{"status": true, "info": "登陆成功"}
	c.ServeJSON()

	models.DelToken(c.GetString("token"))
	go models.SaveLog(username, "登陆", &map[string]interface{}{})

}
